'use client'

import { useState } from 'react'
import { useChat } from 'ai/react'
import ReactMarkdown from 'react-markdown'
import { Card, Button, Input, Typography, Space, Select, message } from 'antd'
import { SendOutlined, CopyOutlined, StopOutlined, CodeOutlined } from '@ant-design/icons'

const { TextArea } = Input
const { Title, Text } = Typography
const { Option } = Select

const PROGRAMMING_LANGUAGES = [
  { value: 'javascript', label: 'JavaScript' },
  { value: 'typescript', label: 'TypeScript' },
  { value: 'python', label: 'Python' },
  { value: 'java', label: 'Java' },
  { value: 'cpp', label: 'C++' },
  { value: 'csharp', label: 'C#' },
  { value: 'go', label: 'Go' },
  { value: 'rust', label: 'Rust' },
  { value: 'php', label: 'PHP' },
  { value: 'ruby', label: 'Ruby' },
]

const CODE_TEMPLATES = [
  '创建一个函数来...',
  '实现一个类，包含...',
  '编写一个算法来...',
  '创建一个API接口...',
  '实现数据验证逻辑...',
  '编写单元测试...',
  '优化现有代码...',
  '重构代码结构...',
]

export default function CodeGenerator() {
  const [input, setInput] = useState('')
  const [language, setLanguage] = useState('javascript')

  const { messages, handleSubmit, isLoading, stop } = useChat({
    api: '/api/generate',
    body: { 
      mode: 'code',
      language 
    },
    onFinish: () => {
      const el = document.getElementById('chat-end')
      el?.scrollIntoView({ behavior: 'smooth', block: 'end' })
    }
  })

  const onSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (input.trim()) {
      const prompt = `请用${PROGRAMMING_LANGUAGES.find(l => l.value === language)?.label}编写代码：${input}`
      handleSubmit(e, { data: { input: prompt } })
      setInput('')
    }
  }

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text)
    message.success('已复制到剪贴板')
  }

  const useTemplate = (template: string) => {
    setInput(template)
  }

  return (
    <div>
      <Title level={2}>代码生成</Title>
      <Text type="secondary">智能代码生成和优化</Text>
      
      <div style={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 200px)' }}>
        {/* 配置区域 */}
        <Card style={{ marginBottom: 16 }}>
          <Space direction="vertical" style={{ width: '100%' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <Text>编程语言：</Text>
              <Select 
                value={language} 
                onChange={setLanguage}
                style={{ width: 150 }}
              >
                {PROGRAMMING_LANGUAGES.map(lang => (
                  <Option key={lang.value} value={lang.value}>
                    {lang.label}
                  </Option>
                ))}
              </Select>
            </div>
            
            <div>
              <Text>快速模板：</Text>
              <div style={{ marginTop: 8, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {CODE_TEMPLATES.map((template, index) => (
                  <Button 
                    key={index}
                    size="small"
                    onClick={() => useTemplate(template)}
                  >
                    {template}
                  </Button>
                ))}
              </div>
            </div>
          </Space>
        </Card>

        {/* 对话区域 */}
        <div style={{ flex: 1, overflowY: 'auto', marginBottom: 16 }}>
          {messages.length === 0 ? (
            <Card>
              <div style={{ textAlign: 'center', padding: '40px 20px' }}>
                <CodeOutlined style={{ fontSize: '48px', color: '#1890ff', marginBottom: '16px' }} />
                <Title level={4}>开始生成代码</Title>
                <Text type="secondary">描述您需要的功能，AI将为您生成相应的代码</Text>
              </div>
            </Card>
          ) : (
            <Space direction="vertical" style={{ width: '100%' }}>
              {messages.map(m => (
                <Card 
                  key={m.id} 
                  size="small"
                  style={{ 
                    borderColor: m.role === 'user' ? '#d9d9d9' : '#f0f0f0',
                    backgroundColor: m.role === 'user' ? '#fff' : '#fafafa'
                  }}
                >
                  <div style={{ marginBottom: 8, fontSize: '12px', color: '#666' }}>
                    {m.role === 'user' ? '你' : '代码生成器'}
                  </div>
                  <div style={{ lineHeight: 1.6 }}>
                    <ReactMarkdown>{m.content || ''}</ReactMarkdown>
                  </div>
                  {m.role !== 'user' && (
                    <div style={{ marginTop: 12 }}>
                      <Button 
                        size="small"
                        onClick={() => copyToClipboard(m.content || '')}
                        icon={<CopyOutlined />}
                      >
                        复制代码
                      </Button>
                    </div>
                  )}
                </Card>
              ))}
              <div id="chat-end" />
            </Space>
          )}
        </div>

        {/* 输入区域 */}
        <Card>
          <form onSubmit={onSubmit}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <TextArea
                value={input}
                onChange={(e) => setInput(e.target.value)}
                placeholder="描述您需要的代码功能..."
                autoSize={{ minRows: 3, maxRows: 6 }}
                onPressEnter={(e) => {
                  if (!e.shiftKey) {
                    e.preventDefault()
                    onSubmit(e as any)
                  }
                }}
              />
              <div style={{ display: 'flex', gap: 8, justifyContent: 'space-between' }}>
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  按 Enter 生成，Shift + Enter 换行
                </Text>
                <Space>
                  {isLoading && (
                    <Button 
                      onClick={() => stop()} 
                      icon={<StopOutlined />}
                    >
                      停止
                    </Button>
                  )}
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    icon={<SendOutlined />}
                    loading={isLoading}
                    disabled={!input.trim()}
                  >
                    生成代码
                  </Button>
                </Space>
              </div>
            </Space>
          </form>
        </Card>
      </div>
    </div>
  )
} 